package com.store.app.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.store.app.R;
import com.store.app.activity.OtherTaskDetailsActivity;
import com.store.app.activity.WillSubmitTaskDetailsActivity;
import com.store.app.adapter.TaskAdapter;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.TaskListBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.ToastUtils;
import com.store.app.widget.AutoListView;
import com.store.app.widget.AutoListView.OnLoadListener;
import com.store.app.widget.AutoListView.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 任务2 除新任务外其他任务
 */
public class Task2Fragment extends Fragment implements IOnHttpListener {
    private View v;
    private AutoListView lv;
    private List<TaskListBean> list;
    private TaskAdapter mAdapter;
    //无网络页面
    private RelativeLayout lin_loadfail;
    private LinearLayout img_fail_notext;
    private TextView tv_fail;
    private static final int MSG_LOAD_SUCCESS = 0;
    private static final int MSG_LOAD_FAILED = 1;
    private static final int MSG_REFRESH_SUCCESS = 2;
    private static final int MSG_REFRESH_FAILED = 3;


    private static final int MSG_DELETE_SUCCESS = 6;
    private static final int MSG_DELETE_FAILED = 7;
    private static final int MSG_LOAD_NOTNET = 8;

    private int pageNum;
    private int pageSize;
    private NetRequest netRequest;
    //通过这个字段判断状态
    //待提交  "status", "submitted"
    //待审核  "status", "audited"
    //待结算  "status", "settled"
    //已完成  "status", "closed"
    private String s_status;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {


                case MSG_LOAD_SUCCESS:
                    Log.v("zyl", "onLoadComplete");
                    lv.onLoadComplete();
                    if (msg.arg1 == pageNum) {
                        @SuppressWarnings("unchecked")
                        List<TaskListBean> result = (List<TaskListBean>) msg.obj;
                        lv.setResultSize(result.size());
                        list.addAll(result);
                        mAdapter.notifyDataSetChanged();
                        pageNum += 1;
                        if (list.size() == 0) {
//                            lin_loadfail.setVisibility(View.VISIBLE);
//                            img_fail_notext.setVisibility(View.VISIBLE);
//                            lin_loadfail.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    lin_loadfail.setVisibility(View.GONE);
//                                    img_fail_notext.setVisibility(View.GONE);
//                                    pageNum = 1;
//                                    if(list!=null){
//                                        list.clear();
//                                    }
//                                    netRequest.requestTaskOrtherList(1, pageNum + "", pageSize + "", s_status);
//                                }
//                            });
                        }
                    }
                    break;
                case MSG_LOAD_FAILED:
                    lv.setResultSize(0);
                    lv.onLoadComplete();

                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case MSG_REFRESH_SUCCESS:
                    lv.onLoadComplete();
                    lv.onRefreshComplete();
                    @SuppressWarnings("unchecked")
                    List<TaskListBean> result = (List<TaskListBean>) msg.obj;
                    lv.setResultSize(result.size());
                    list.clear();
                    list.addAll(result);
                    mAdapter.notifyDataSetChanged();
                    pageNum += 1;
                    break;
                case MSG_REFRESH_FAILED:
                    lv.onRefreshComplete();
                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case MSG_DELETE_SUCCESS:
                    lv.onRefresh();
                    break;
                case MSG_DELETE_FAILED:
                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                //无网络
                case MSG_LOAD_NOTNET:
//                    lin_loadfail.setVisibility(View.VISIBLE);
//                    img_fail_notext.setVisibility(View.VISIBLE);
//                    lin_loadfail.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            lin_loadfail.setVisibility(View.GONE);
//                            img_fail_notext.setVisibility(View.GONE);
//                            pageNum = 1;
//                            if(list!=null){
//                                list.clear();
//                            }
//                            netRequest.requestTaskOrtherList(1, pageNum + "", pageSize + "", s_status);
//                        }
//                    });
                default:
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_task, container, false);
        list = new ArrayList<>();
        s_status= getArguments().getString("status");
        pageNum = 1;
        pageSize = 15;
        findViews();
        setListeners();
        lv.onLoad();
        EventBus.getDefault().register(this);
        return v;
    }

    //    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(EventBusBean eventBusBean){
        Log.v("zyl","收到信号要去刷新页面");
//        if(eventBusBean.type == 206){
//            pageNum = 1;
//            netRequest.requestTaskOrtherList(2, pageNum + "", pageSize + "",s_status);
//        }
        //刷新待提交页面
        if(eventBusBean.type == 224){
            if(s_status.equals("submitted")){
                lin_loadfail.setVisibility(View.GONE);
                img_fail_notext.setVisibility(View.GONE);
                pageNum = 1;
                netRequest.requestTaskOrtherList(2, pageNum + "", pageSize + "",s_status);
            }
        }else if(eventBusBean.type == 225){
            if(s_status.equals("audited")){
                lin_loadfail.setVisibility(View.GONE);
                img_fail_notext.setVisibility(View.GONE);
                pageNum = 1;
                netRequest.requestTaskOrtherList(2, pageNum + "", pageSize + "",s_status);
            }
        }

    }



    private void findViews() {
        netRequest = new NetRequest(this, getActivity());
        lv = (AutoListView) v.findViewById(R.id.lv_task);
        lv.setDivider(null);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position<=list.size()&&position>0) {
                    if (s_status != null) {
                        if (s_status.equals("submitted")) {
                            Intent intent = new Intent(getActivity(), WillSubmitTaskDetailsActivity.class);
                            intent.putExtra("processing_id", list.get(position - 1).getProcessing_id());
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(getActivity(), OtherTaskDetailsActivity.class);
                            intent.putExtra("processing_id", list.get(position - 1).getProcessing_id());
                            startActivity(intent);
                        }
                    }
                }
            }
        });

        mAdapter = new TaskAdapter( getActivity(),list);
        lv.setAdapter(mAdapter);
        lin_loadfail= (RelativeLayout) v.findViewById(R.id.loadfail);
        img_fail_notext= (LinearLayout) v.findViewById(R.id.ll_load_null);
        tv_fail= (TextView) v.findViewById(R.id.loadfail_tv);
        tv_fail.setText("暂无任务");
    }


    private void setListeners() {


        lv.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                pageNum = 1;
                netRequest.requestTaskOrtherList(2, pageNum + "", pageSize + "",s_status);
            }
        });

        lv.setOnLoadListener(new OnLoadListener() {

            @Override
            public void onLoad() {
                netRequest.requestTaskOrtherList(1, pageNum + "", pageSize + "",s_status);

            }
        });
    }

    @Override
    public void onAfinalFail() {

        if (getActivity() != null) {
            ToastUtils.showTextToast(getActivity(), "请检查本地网络！");
        }
        if (lv != null) {
            lv.onRefreshComplete();
        }
//        if( pageNum ==1) {
//            Message message = Message.obtain();
//            message.what = MSG_LOAD_NOTNET;
//            mHandler.sendMessage(message);
//        }
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            try {
                JSONObject data = new JSONObject(result);
                Log.v("zyl", "data1:"+s_status+"eeeeeee" + data.toString());
                Gson gson = new Gson();

                JSONArray listArr = data.getJSONArray("list");
                List<TaskListBean> OrderBeanList = new ArrayList<>();
                for (int i = 0; i < listArr.length(); i++) {
                    TaskListBean orderBean = gson.fromJson(listArr.getJSONObject(i).toString(), TaskListBean.class);
                    OrderBeanList.add(orderBean);
                }
                Message message = Message.obtain();
                message.what = MSG_LOAD_SUCCESS;
                message.arg1 = data.getJSONObject("page").getInt("page_no");
                message.obj = OrderBeanList;
                mHandler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 2) {
            try {
                JSONObject data = new JSONObject(result);
                Gson gson = new Gson();
                JSONArray listArr = data.getJSONArray("list");
                List<TaskListBean> OrderBeanList = new ArrayList<>();
                for (int i = 0; i < listArr.length(); i++) {
                    TaskListBean orderBean = gson.fromJson(listArr.getJSONObject(i).toString(), TaskListBean.class);
                    OrderBeanList.add(orderBean);
                }
                Message message = Message.obtain();
                message.what = MSG_REFRESH_SUCCESS;
                message.arg1 = data.getJSONObject("page").getInt("page_no");
                Log.v("zyl", "订单数据：" + data.getString("list"));
                message.obj = OrderBeanList;
                mHandler.sendMessage(message);
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (msg.contains("重新登")) {

        } else {
            if (getActivity() != null) {
                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            }
        }
    }

}